package com.hui.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hui.admin.common.enums.ErrorCodeEnum;
import com.hui.admin.common.exception.UserException;
import com.hui.admin.dto.request.LogPageRequestDTO;
import com.hui.admin.dto.response.LogPageResponseDTO;
import com.hui.admin.entity.LogDO;
import com.hui.admin.mapper.LogMapper;
import com.hui.admin.service.LogService;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Service
public class LogServiceImpl extends ServiceImpl<LogMapper, LogDO> implements LogService {
    @Override
    public LogPageResponseDTO getLogPageList(LogPageRequestDTO requestDTO) {
        Page<LogDO> page = new Page<>(requestDTO.getPageNum(), requestDTO.getPageSize());
        LambdaQueryWrapper<LogDO> queryWrapper = new LambdaQueryWrapper<>();
        if (requestDTO.getMethod() != null) {
            queryWrapper.eq(LogDO::getMethod, requestDTO.getMethod());
        }
        if (requestDTO.getUsername() != null) {
            queryWrapper.like(LogDO::getUsername, requestDTO.getUsername());
        }
        Page<LogDO> resultLogList = baseMapper.selectPage(page, queryWrapper);
        LogPageResponseDTO result = new LogPageResponseDTO();
        result.setList(resultLogList.getRecords());
        result.setTotal(resultLogList.getTotal());
        return result;
    }

    @Override
    public void deleteLogs(Long[] ids) {
        if (ids == null || ids.length == 0) {
            throw new UserException(ErrorCodeEnum.INVALID_PARAMS);
        }
        boolean success = removeByIds(Arrays.asList(ids));
        if (!success) {
            throw new UserException(ErrorCodeEnum.DELETE_FAILED);
        }
    }
}
